import { warn as u } from '../log.js';
import { createStringifyContext as d } from '../stringify/stringify.js';
import {
  isAlias as c,
  isSeq as S,
  isScalar as g,
  isMap as y,
  isNode as b,
} from './identity.js';
import { Scalar as p } from './Scalar.js';
import { toJS as f } from './toJS.js';
const a = '<<';
function m(r, e, { key: i, value: o }) {
  if (r != null && r.doc.schema.merge && M(i))
    if (((o = c(o) ? o.resolve(r.doc) : o), S(o)))
      for (const n of o.items) l(r, e, n);
    else if (Array.isArray(o)) for (const n of o) l(r, e, n);
    else l(r, e, o);
  else {
    const n = f(i, '', r);
    if (e instanceof Map) e.set(n, f(o, n, r));
    else if (e instanceof Set) e.add(n);
    else {
      const t = h(i, n, r),
        s = f(o, t, r);
      t in e
        ? Object.defineProperty(e, t, {
            value: s,
            writable: !0,
            enumerable: !0,
            configurable: !0,
          })
        : (e[t] = s);
    }
  }
  return e;
}
const M = r =>
  r === a || (g(r) && r.value === a && (!r.type || r.type === p.PLAIN));
function l(r, e, i) {
  const o = r && c(i) ? i.resolve(r.doc) : i;
  if (!y(o)) throw new Error('Merge sources must be maps or map aliases');
  const n = o.toJSON(null, r, Map);
  for (const [t, s] of n)
    e instanceof Map
      ? e.has(t) || e.set(t, s)
      : e instanceof Set
        ? e.add(t)
        : Object.prototype.hasOwnProperty.call(e, t) ||
          Object.defineProperty(e, t, {
            value: s,
            writable: !0,
            enumerable: !0,
            configurable: !0,
          });
  return e;
}
function h(r, e, i) {
  if (e === null) return '';
  if (typeof e != 'object') return String(e);
  if (b(r) && i != null && i.doc) {
    const o = d(i.doc, {});
    o.anchors = /* @__PURE__ */ new Set();
    for (const t of i.anchors.keys()) o.anchors.add(t.anchor);
    (o.inFlow = !0), (o.inStringifyKey = !0);
    const n = r.toString(o);
    if (!i.mapKeyWarned) {
      let t = JSON.stringify(n);
      t.length > 40 && (t = t.substring(0, 36) + '..."'),
        u(
          i.doc.options.logLevel,
          `Keys with collection values will be stringified due to JS Object restrictions: ${t}. Set mapAsMap: true to use object keys.`,
        ),
        (i.mapKeyWarned = !0);
    }
    return n;
  }
  return JSON.stringify(e);
}
export { m as addPairToJSMap };
